package com.zyx.xunyilu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zyx.xunyilu.config.jwt.JWTUtils;
import com.zyx.xunyilu.mapper.CtosMapper;
import com.zyx.xunyilu.utils.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @ClassName: CtosController
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2019/11/16 17:08
 */
@CrossOrigin
@Slf4j
@RestController
public class CtosController {

    @Autowired
    CtosMapper ctosMapper;

    @Autowired
    JWTUtils jwtUtils;

    @ModelAttribute
    public void setToken(HttpServletRequest request,
                         @RequestHeader(value = "token", required = false, defaultValue = "") String headerToken,
                         @RequestParam(value = "token", required = false) String pToken) {
        String token = headerToken;
        if (StringUtils.isEmpty(token)) {
            token = pToken;
        }
        request.setAttribute("token", token);
    }

    @PostMapping("/getCtos")
    public RestResponse getList(@RequestParam("ctos[]") List<String> ctos,
                                @RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                @RequestParam(value = "size", required = false, defaultValue = "10") Integer size,
                                @RequestAttribute("token") String token) throws Exception {
        if (page < 0 || size < 0) {
            throw new RuntimeException("传入的值错误!");
        }
        String username = jwtUtils.getUsername(token);
        log.info("{} -查询了{}", username, ctos);
        if (ctos.isEmpty()) {
            throw new RuntimeException("传入的值不能为空!");
        }
        Page<String> pageParam = new Page<>(page, size);
        IPage<String> list = ctosMapper.getList(pageParam, ctos);
        return RestResponse.ok(list);
    }

}